import React from "react";
import { NavLink, Link } from "react-router-dom";
import { Button, Input, Form } from "antd";
import md5 from 'md5';
import { teacherLogin, getTeaLoginValidCode } from '../api';
import http from 'libs/http'
import * as utils from 'libs/utils'

const ButtonGroup = Button.Group;
const FormItem = Form.Item;

class TeacherLogin extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      validCodeImg: '',
      showErr: false,
      errMessage: 'cuowu tingshi xinxi'
    }
  }

  componentDidMount() {
    this.getTeaLoginValidCode()
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      const { password:_password, ...rest } = values
      if (!err) {
        teacherLogin({ password: md5(_password), ...rest }, res => {
          this.props.history.push('/teacher/gerenxinxi')
        }, err => {
          console.log('err', err)
          this.setState({
            showErr: true,
            errMessage: utils.teacherTransformErr(err)
          })
          this.getTeaLoginValidCode()
        })
      }
    });
  }

  getTeaLoginValidCode = () => {
    getTeaLoginValidCode(res => {
      this.setState({
        validCodeImg: res.data
      })
    })
  }
  onChange = () => {
    this.setState({ showErr: false, errMessage: '' })
  }

  validateEmail = (rule, value, callback) => {
    if (value && !/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(value)) {
      callback('Email format incorrect!');
    } else {
      http.get('/teacher/common/validEmail', {email: value})
      .then(res => {
        if(res.data) {
          callback();
        }else {
          callback(<div>No account yet ? <Link  to="/teacher/register_pad">Register now</Link></div>)
        }
      })
    }
  }


  render() {

    const { validCodeImg, showErr, errMessage } = this.state
    const { getFieldDecorator } = this.props.form

    return (
      <div className="teacher-registry">
        <div className="registry-header">
          <span className="title">LOGIN</span>
          <span className="toLogin">
            <span>No account yet？</span><br/>
            <NavLink to="/teacher/register_pad">Register now</NavLink>
          </span>
        </div>
        <Form onSubmit={this.handleSubmit}
          onKeyDown={(e) => {
            if (e.keyCode == 13) {
              e.preventDefault();
            }
          }}
        >
          <FormItem style={{ marginBottom: 0, minHeight: 50 }}>
            {getFieldDecorator('email', {
              rules: [
                { required: true, message: "Please don't leave this blank!" },
                { validator: this.validateEmail },
              ],
            })(
              <Input onChange={this.onChange} placeholder="Enter your email" autoComplete="off" />
            )}
          </FormItem>
          <FormItem style={{ marginBottom: 0, minHeight: 50 }}>
            {getFieldDecorator('password', {
              rules: [
                { required: true, message: "Please don't leave this blank!" },
                { pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,30}$/, message: 'The password should be a 6-20' +

                    ' digit combination of digital ciphers'}
              ],
            })(
              <p><Input onChange={this.onChange} type="password" placeholder="Enter your Password" autoComplete="off" /></p>
            )}
          </FormItem>
          <FormItem style={{ marginBottom: 0, minHeight: 50 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              {getFieldDecorator('validCode', {
                rules: [
                  { required: true, message: "Please don't leave this blank!" },
                ],
              })(<p style={{ flex: 1 , marginRight: 20 }}><Input placeholder="Verification code" autoComplete="off" /></p>)}
              <div style={{ width: 100, height: 32 }} onClick={this.getTeaLoginValidCode}>
                <img style={{ width: 100, height: 32, cursor: 'pointer', float: 'left' }} src={validCodeImg} alt="" />
              </div>
            </div>
          </FormItem>
          <p style={{color: 'red', textIndent: 8, fontSize: 14, display: `${showErr?'inline-block':'none'}`}}>{errMessage}</p>
          <FormItem>
            <NavLink to="/teacher/forget_password_pad" className="forget">Forget the password?</NavLink>
          </FormItem>
          <Button type="primary" className="registry-btn" htmlType="submit">LOGIN</Button>
        </Form>
      </div>
    );
  }
}

const WrapTeacherLogin = Form.create()(TeacherLogin)
export default WrapTeacherLogin
